<template>
  <div class="p-6 space-y-4" v-if="showInfoForm">
    <el-card shadow="never" class="rounded-lg">
      <div class="flex items-center justify-end mb-5">
        <el-button @click="onReturnTable">
          <svg-icon icon-class="return" class="mr-2"></svg-icon>
          返回
        </el-button>
        <el-button type="primary" @click="onSave" v-if="!disabled">
          <svg-icon icon-class="save" class="mr-2"></svg-icon>
          保存
        </el-button>
      </div>
      <el-form ref="basicInfoForm" :model="infoForm" :rules="rules" label-position="top" label-width="150px">
        <el-row :gutter="12" align="bottom">
          <el-col :span="4">
            <el-form-item label="顶上事件名称" prop="topEvent">
              <el-input v-model="infoForm.topEvent" :disabled="disabled" placeholder="请输入顶上事件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="所属装置" prop="device">
              <el-select v-model="infoForm.device" :disabled="disabled" placeholder="请选择所属装置" clearable>
                <el-option v-for="c in deviceOptions" :key="c" :label="c" :value="c" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="所属单元" prop="unit">
              <el-input v-model="infoForm.unit" :disabled="disabled" placeholder="请输入所属单元" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="风险场景分类" prop="riskType">
              <el-input v-model="infoForm.riskType" :disabled="disabled" placeholder="请输入风险场景分类" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="危险源" prop="hazardSource">
              <el-input v-model="infoForm.hazardSource" :disabled="disabled" placeholder="请输入危险源" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="危险源设备位号" prop="hazardSourceEqNumNames">
              <el-input-tag
                :disabled="disabled"
                v-model="infoForm.hazardSourceEqNumNames"
                clearable
                @remove-tag="removeEqTag"
                @clear="clearEqData"
                placeholder="请输入危险源设备位号"
              >
                <template #suffix>
                  <el-button :icon="Search" @click="changeSelectHazardSourceEqNum" />
                </template>
              </el-input-tag>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="风险场景分类" prop="riskCode">
              <el-input v-model="infoForm.riskCode" :disabled="disabled" placeholder="请输入风险场景分类" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="原因/后果设备位号" prop="initialRisk">
              <el-input v-model="infoForm.initialRisk" :disabled="disabled" placeholder="请输入原因/后果设备位号" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="使用条件概率" prop="riskType">
              <el-input v-model="infoForm.causesAndConsequences" :disabled="disabled" placeholder="请输入使用条件概率" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="后果修饰概率" prop="useProbability">
              <el-input v-model="infoForm.useProbability" :disabled="disabled" placeholder="请输入后果修饰概率" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="始发事件概率" prop="consequencesProbability">
              <el-input v-model="infoForm.consequencesProbability" :disabled="disabled" placeholder="请输入始发事件概率" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="初始风险" prop="startProbability">
              <el-input v-model="infoForm.startProbability" :disabled="disabled" placeholder="请输入初始风险" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <barrier-table ref="barrierTableRef" :show-btn="!disabled" />
    <hazard-source-eq-num-select :ids="infoForm.hazardSourceEqNumIds" ref="hazardSourceEqNumSelectRef" @change-select-data="changeSelectData" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { Search } from '@element-plus/icons-vue';
import HazardSourceEqNumSelect from './components/HazardSourceEqNumSelect.vue';
import BarrierTable from './components/BarrierTable.vue';
import { DeviceRow } from './components/constant';

type FormType = 'ADD' | 'EDIT' | 'VIEW';

interface BasicInfoForm {
  id?: number;
  // 顶上事件名称
  topEvent: string;
  // 所属装置
  device: string;
  // 所属单元
  unit: string;
  // 风险场景分类
  riskType: string;
  // 危险源
  hazardSource: string;
  // 危险源设备位号
  hazardSourceEqNum: string;
  hazardSourceEqNumIds: number[];
  hazardSourceEqNumNames: string[];
  hazardSourceEqNumNamesCopy: string[];
  // 风险清单编号
  riskCode: string;
  // 原因/后果设备位号
  initialRisk: string;
  // 使用条件概率
  causesAndConsequences: string;
  // 后果修饰概率
  useProbability: string;
  // 始发事件概率
  consequencesProbability: string;
  // 初始风险
  startProbability: string;
}

const emits = defineEmits(['returnTable']);

const DEFAULT_FORM: BasicInfoForm = {
  id: undefined,
  // 顶上事件名称
  topEvent: '',
  // 所属装置
  device: '',
  // 所属单元
  unit: '',
  // 风险场景分类
  riskType: '',
  // 危险源
  hazardSource: '',
  // 危险源设备位号
  hazardSourceEqNum: '',
  hazardSourceEqNumIds: [],
  hazardSourceEqNumNames: [],
  hazardSourceEqNumNamesCopy: [],
  // 风险清单编号
  riskCode: '',
  // 原因/后果设备位号
  initialRisk: '',
  // 使用条件概率
  causesAndConsequences: '',
  // 后果修饰概率
  useProbability: '',
  // 始发事件概率
  consequencesProbability: '',
  // 初始风险
  startProbability: ''
};

// 表单信息
const infoForm = ref<BasicInfoForm>({ ...DEFAULT_FORM });
// 表单类型
const formType = ref<FormType>('ADD');

const disabled = computed(() => formType.value === 'VIEW');

// 表单校验
const rules = ref({
  tableName: [{ required: true, message: '请输入表名称', trigger: 'blur' }],
  tableComment: [{ required: true, message: '请输入表描述', trigger: 'blur' }],
  className: [{ required: true, message: '请输入实体类名称', trigger: 'blur' }],
  functionAuthor: [{ required: true, message: '请输入作者', trigger: 'blur' }]
});

const deviceOptions = ['装置1', '装置2', '装置3'];

const barrierTableRef = ref(null);
const hazardSourceEqNumSelectRef = ref(null);
const showInfoForm = ref(false);

const openForm = (type: FormType, id?: number) => {
  formType.value = type;
  resetForm();
  if (id) {
    getFormInfoById(id);
  }
  showInfoForm.value = true;
};

const getFormInfoById = (id: number) => {};

const resetForm = () => {
  infoForm.value = { ...DEFAULT_FORM };
};

const onReturnTable = () => {
  showInfoForm.value = false;
  emits('returnTable');
};

const onSave = () => {
  switch (formType.value) {
    case 'ADD': {
      break;
    }
    case 'EDIT': {
      break;
    }
    case 'VIEW': {
      break;
    }
    default:
      break;
  }
  onReturnTable();
};

const changeSelectHazardSourceEqNum = () => {
  if (disabled.value) return;
  hazardSourceEqNumSelectRef.value?.open();
};

const clearEqData = () => {
  infoForm.value.hazardSourceEqNumIds = [];
  infoForm.value.hazardSourceEqNumNames = [];
  infoForm.value.hazardSourceEqNumNamesCopy = [];
};

const removeEqTag = (value: string) => {
  const index = infoForm.value.hazardSourceEqNumNamesCopy.indexOf(value);
  if (index !== -1) {
    infoForm.value.hazardSourceEqNumIds.splice(index, 1);
  }
};

const changeSelectData = (data: DeviceRow[]) => {
  const ids = [];
  const names = [];
  if (data && data.length > 0) {
    data.forEach((item) => {
      ids.push(item.id);
      names.push(item.deviceName);
    });
  }
  infoForm.value.hazardSourceEqNumIds = ids;
  infoForm.value.hazardSourceEqNumNames = names;
  infoForm.value.hazardSourceEqNumNamesCopy = names;
};

defineExpose({ openForm });
</script>
